import {ref} from "vue";
import {bStorage, bProxy, bService} from '../api'

const clientId = ref('');
const rules = ref([]);
const defaultEnabled = ref(false);
const allowMultipleChoice = ref(false);
const defaultRules = ref('');
const server = ref({});
const apiUrl = ref('');
const hasInit = ref(false);
const proxyEnabled = ref(false);
const autoRefresh = ref(false);

;(async () => {
  apiUrl.value = await bStorage.getApiUrl()
  autoRefresh.value = (await bStorage.get('auto-refresh')) === true
})()
const getProxyStatus = async () => {
  proxyEnabled.value = await bProxy.get();
}

const processInfo = (rules) => {
  const data = [];
  let pItem;
  rules.forEach(item => {
    if (item.name.match(/^\r/)) {
      pItem = {...item, name: item.name.replace(/^\r/, ''), children: []}
      data.push(pItem)
    } else {
      if (pItem) {
        pItem.children.push(item)
      } else {
        data.push(item)
      }
    }
  })
  return data
}

const getInitInfo = async () => {
  try {
    let res = await bService.getInitInfo();
    clientId.value = res.clientId;
    rules.value = processInfo(res.rules.list);
    defaultEnabled.value = !res.rules.defaultRulesIsDisabled;
    allowMultipleChoice.value = res.rules.allowMultipleChoice;
    defaultRules.value = res.rules.defaultRules;
    server.value = res.server;
    return true;
  } catch (e) {
    rules.value = null;
    return false;
  }
}

const init = async (needReset) => {
  if (needReset) {
    hasInit.value = false;
  }
  await getProxyStatus();
  await getInitInfo();
  hasInit.value = true;
}
export {
  init,
  getInitInfo,
  getProxyStatus,
  clientId,
  rules,
  defaultEnabled,
  allowMultipleChoice,
  defaultRules,
  server,
  apiUrl,
  hasInit,
  autoRefresh,
  proxyEnabled
}
